<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-minimal.min.css">
  <script src="/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"yoursite.com","root":"/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":true,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":-1,"unescape":false,"preload":true},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"./public/search.xml"};
  </script>

  <meta name="description" content="原文连接 AJAX 简介什么是 AJAX ？AJAX &#x3D; 异步 JavaScript 和 XML。 AJAX 是一种用于创建快速动态网页的技术。 通过在后台与服务器进行少量数据交换，AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下，对网页的某部分进行更新。 传统的网页（不使用 AJAX）如果需要更新内容，必需重载整个网页面。 有很多使用 AJAX 的应用程序案例：新浪微">
<meta property="og:type" content="article">
<meta property="og:title" content="AJAX 简介">
<meta property="og:url" content="http://yoursite.com/2020/07/13/AJAX%20%E7%AE%80%E4%BB%8B/index.html">
<meta property="og:site_name" content="GipBaby270&#39;s Blog">
<meta property="og:description" content="原文连接 AJAX 简介什么是 AJAX ？AJAX &#x3D; 异步 JavaScript 和 XML。 AJAX 是一种用于创建快速动态网页的技术。 通过在后台与服务器进行少量数据交换，AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下，对网页的某部分进行更新。 传统的网页（不使用 AJAX）如果需要更新内容，必需重载整个网页面。 有很多使用 AJAX 的应用程序案例：新浪微">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://i.loli.net/2020/07/13/qk9cJVwE4QmMuhj.png">
<meta property="og:image" content="https://www.runoob.com/wp-content/uploads/2013/09/ajax-yl.png">
<meta property="og:image" content="https://www.runoob.com/images/lamp.gif">
<meta property="article:published_time" content="2020-07-13T08:58:06.742Z">
<meta property="article:modified_time" content="2020-07-13T08:59:20.988Z">
<meta property="article:author" content="Gip886">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://i.loli.net/2020/07/13/qk9cJVwE4QmMuhj.png">

<link rel="canonical" href="http://yoursite.com/2020/07/13/AJAX%20%E7%AE%80%E4%BB%8B/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>AJAX 简介 | GipBaby270's Blog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    
    <a href="https://github.com/Gip886" target="_blank" rel="noopener" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#64CEAA; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
    
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">GipBaby270's Blog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Fighting for BAT!</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/07/13/AJAX%20%E7%AE%80%E4%BB%8B/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/%E5%A4%B4%E5%83%8F.jpg">
      <meta itemprop="name" content="Gip886">
      <meta itemprop="description" content="为了更美好的明天而战">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="GipBaby270's Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          AJAX 简介
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2020-07-13 16:58:06 / 修改时间：16:59:20" itemprop="dateCreated datePublished" datetime="2020-07-13T16:58:06+08:00">2020-07-13</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/JS%E5%9F%BA%E7%A1%80/" itemprop="url" rel="index"><span itemprop="name">JS基础</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span><br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>4.8k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>4 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p><img src="https://i.loli.net/2020/07/13/qk9cJVwE4QmMuhj.png" alt></p>
<p><a href="https://www.runoob.com/ajax/ajax-tutorial.html" target="_blank" rel="noopener">原文连接</a></p>
<h1 id="AJAX-简介"><a href="#AJAX-简介" class="headerlink" title="AJAX 简介"></a>AJAX 简介</h1><h2 id="什么是-AJAX-？"><a href="#什么是-AJAX-？" class="headerlink" title="什么是 AJAX ？"></a>什么是 AJAX ？</h2><p>AJAX = 异步 JavaScript 和 XML。</p>
<p>AJAX 是一种用于创建快速动态网页的技术。</p>
<p>通过在后台与服务器进行少量数据交换，AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下，对网页的某部分进行更新。</p>
<p>传统的网页（不使用 AJAX）如果需要更新内容，必需重载整个网页面。</p>
<p>有很多使用 AJAX 的应用程序案例：新浪微博、Google 地图、开心网等等。</p>
<a id="more"></a>

<h2 id="AJAX-工作原理"><a href="#AJAX-工作原理" class="headerlink" title="AJAX 工作原理"></a>AJAX 工作原理</h2><p><img src="https://www.runoob.com/wp-content/uploads/2013/09/ajax-yl.png" alt="AJAX"></p>
<h2 id="AJAX是基于现有的Internet标准"><a href="#AJAX是基于现有的Internet标准" class="headerlink" title="AJAX是基于现有的Internet标准"></a>AJAX是基于现有的Internet标准</h2><p>AJAX是基于现有的Internet标准，并且联合使用它们：</p>
<ul>
<li>XMLHttpRequest 对象 (异步的与服务器交换数据)</li>
<li>JavaScript/DOM (信息显示/交互)</li>
<li>CSS (给数据定义样式)</li>
<li>XML (作为转换数据的格式)</li>
</ul>
<p><img src="https://www.runoob.com/images/lamp.gif" alt="lamp"> AJAX应用程序与浏览器和平台无关的！</p>
<h1 id="AJAX-创建-XMLHttpRequest-对象"><a href="#AJAX-创建-XMLHttpRequest-对象" class="headerlink" title="AJAX - 创建 XMLHttpRequest 对象"></a>AJAX - 创建 XMLHttpRequest 对象</h1><hr>
<p>XMLHttpRequest 是 AJAX 的基础。</p>
<h2 id="XMLHttpRequest-对象"><a href="#XMLHttpRequest-对象" class="headerlink" title="XMLHttpRequest 对象"></a>XMLHttpRequest 对象</h2><p>所有现代浏览器均支持 XMLHttpRequest 对象（IE5 和 IE6 使用 ActiveXObject）。</p>
<p>XMLHttpRequest 用于在后台与服务器交换数据。这意味着可以在不重新加载整个网页的情况下，对网页的某部分进行更新。</p>
<h2 id="创建-XMLHttpRequest-对象"><a href="#创建-XMLHttpRequest-对象" class="headerlink" title="创建 XMLHttpRequest 对象"></a>创建 XMLHttpRequest 对象</h2><p>所有现代浏览器（IE7+、Firefox、Chrome、Safari 以及 Opera）均内建 XMLHttpRequest 对象。</p>
<p>创建 XMLHttpRequest 对象的语法：</p>
<p><code>*variable*=new XMLHttpRequest();</code></p>
<p>老版本的 Internet Explorer （IE5 和 IE6）使用 ActiveX 对象：</p>
<p><code>*variable*=new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;);</code></p>
<p>为了应对所有的现代浏览器，包括 IE5 和 IE6，请检查浏览器是否支持 XMLHttpRequest 对象。如果支持，则创建 XMLHttpRequest 对象。如果不支持，则创建 ActiveXObject ：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">var xmlhttp;</span><br><span class="line">if (window.XMLHttpRequest)</span><br><span class="line">&#123;</span><br><span class="line">    &#x2F;&#x2F;  IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码</span><br><span class="line">    xmlhttp&#x3D;new XMLHttpRequest();</span><br><span class="line">&#125;</span><br><span class="line">else</span><br><span class="line">&#123;</span><br><span class="line">    &#x2F;&#x2F; IE6, IE5 浏览器执行代码</span><br><span class="line">    xmlhttp&#x3D;new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="AJAX-向服务器发送请求请求"><a href="#AJAX-向服务器发送请求请求" class="headerlink" title="AJAX - 向服务器发送请求请求"></a>AJAX - 向服务器发送请求请求</h1><hr>
<p>XMLHttpRequest 对象用于和服务器交换数据。</p>
<h2 id="向服务器发送请求"><a href="#向服务器发送请求" class="headerlink" title="向服务器发送请求"></a>向服务器发送请求</h2><p>如需将请求发送到服务器，我们使用 XMLHttpRequest 对象的 open() 和 send() 方法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">xmlhttp.open(&quot;GET&quot;,&quot;ajax_info.txt&quot;,true);</span><br><span class="line">xmlhttp.send();</span><br></pre></td></tr></table></figure>



<table>
<thead>
<tr>
<th align="left">方法</th>
<th align="left">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="left">open(<em>method</em>,<em>url</em>,<em>async</em>)</td>
<td align="left">规定请求的类型、URL 以及是否异步处理请求。<em>method</em>：请求的类型；GET 或 POST<em>url</em>：文件在服务器上的位置<em>async</em>：true（异步）或 false（同步）</td>
</tr>
<tr>
<td align="left">send(<em>string</em>)</td>
<td align="left">将请求发送到服务器。<em>string</em>：仅用于 POST 请求</td>
</tr>
</tbody></table>
<h2 id="GET-还是-POST？"><a href="#GET-还是-POST？" class="headerlink" title="GET 还是 POST？"></a>GET 还是 POST？</h2><p>与 POST 相比，GET 更简单也更快，并且在大部分情况下都能用。</p>
<p>然而，在以下情况中，请使用 POST 请求：</p>
<ul>
<li>无法使用缓存文件（更新服务器上的文件或数据库）</li>
<li>向服务器发送大量数据（POST 没有数据量限制）</li>
<li>发送包含未知字符的用户输入时，POST 比 GET 更稳定也更可靠</li>
</ul>
<h2 id="GET-请求"><a href="#GET-请求" class="headerlink" title="GET 请求"></a>GET 请求</h2><p>一个简单的 GET 请求：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">xmlhttp.open(&quot;GET&quot;,&quot;&#x2F;try&#x2F;ajax&#x2F;demo_get.php&quot;,true);</span><br><span class="line">xmlhttp.send();</span><br></pre></td></tr></table></figure>

<p>在上面的例子中，您可能得到的是缓存的结果。</p>
<p>为了避免这种情况，请向 URL 添加一个唯一的 ID：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">xmlhttp.open(&quot;GET&quot;,&quot;&#x2F;try&#x2F;ajax&#x2F;demo_get.php?t&#x3D;&quot; + Math.random(),true);</span><br><span class="line">xmlhttp.send();</span><br></pre></td></tr></table></figure>

<p>如果您希望通过 GET 方法发送信息，请向 URL 添加信息：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">xmlhttp.open(&quot;GET&quot;,&quot;&#x2F;try&#x2F;ajax&#x2F;demo_get2.php?fname&#x3D;Henry&amp;lname&#x3D;Ford&quot;,true);</span><br><span class="line">xmlhttp.send();</span><br></pre></td></tr></table></figure>

<h2 id="POST-请求"><a href="#POST-请求" class="headerlink" title="POST 请求"></a>POST 请求</h2><p>一个简单 POST 请求：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">xmlhttp.open(&quot;POST&quot;,&quot;&#x2F;try&#x2F;ajax&#x2F;demo_post.php&quot;,true);</span><br><span class="line">xmlhttp.send();</span><br></pre></td></tr></table></figure>

<p>如果需要像 HTML 表单那样 POST 数据，请使用 setRequestHeader() 来添加 HTTP 头。然后在 send() 方法中规定您希望发送的数据：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">xmlhttp.open(&quot;POST&quot;,&quot;&#x2F;try&#x2F;ajax&#x2F;demo_post2.php&quot;,true);</span><br><span class="line">xmlhttp.setRequestHeader(&quot;Content-type&quot;,&quot;application&#x2F;x-www-form-urlencoded&quot;);</span><br><span class="line">xmlhttp.send(&quot;fname&#x3D;Henry&amp;lname&#x3D;Ford&quot;);</span><br></pre></td></tr></table></figure>

<table>
<thead>
<tr>
<th align="left">方法</th>
<th align="left">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="left">setRequestHeader(<em>header,value</em>)</td>
<td align="left">向请求添加 HTTP 头。<em>header</em>: 规定头的名称<em>value</em>: 规定头的值</td>
</tr>
</tbody></table>
<h2 id="url-服务器上的文件"><a href="#url-服务器上的文件" class="headerlink" title="url - 服务器上的文件"></a>url - 服务器上的文件</h2><p>open() 方法的 <em>url</em> 参数是服务器上文件的地址：</p>
<p><code>xmlhttp.open(&quot;GET&quot;,&quot;ajax_test.html&quot;,true);</code></p>
<p>该文件可以是任何类型的文件，比如 .txt 和 .xml，或者服务器脚本文件，比如 .asp 和 .php （在传回响应之前，能够在服务器上执行任务）。</p>
<h2 id="异步-True-或-False？"><a href="#异步-True-或-False？" class="headerlink" title="异步 - True 或 False？"></a>异步 - True 或 False？</h2><p>AJAX 指的是异步 JavaScript 和 XML（Asynchronous JavaScript and XML）。</p>
<p>XMLHttpRequest 对象如果要用于 AJAX 的话，其 open() 方法的 async 参数必须设置为 true：</p>
<p><code>xmlhttp.open(&quot;GET&quot;,&quot;ajax_test.html&quot;,true);</code></p>
<p>对于 web 开发人员来说，发送异步请求是一个巨大的进步。很多在服务器执行的任务都相当费时。AJAX 出现之前，这可能会引起应用程序挂起或停止。</p>
<p>通过 AJAX，JavaScript 无需等待服务器的响应，而是：</p>
<ul>
<li>在等待服务器响应时执行其他脚本</li>
<li>当响应就绪后对响应进行处理</li>
</ul>
<h1 id="AJAX-服务器-响应"><a href="#AJAX-服务器-响应" class="headerlink" title="AJAX - 服务器 响应"></a>AJAX - 服务器 响应</h1><hr>
<h2 id="服务器响应"><a href="#服务器响应" class="headerlink" title="服务器响应"></a>服务器响应</h2><p>如需获得来自服务器的响应，请使用 XMLHttpRequest 对象的 responseText 或 responseXML 属性。</p>
<table>
<thead>
<tr>
<th align="left">属性</th>
<th align="left">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="left">responseText</td>
<td align="left">获得字符串形式的响应数据。</td>
</tr>
<tr>
<td align="left">responseXML</td>
<td align="left">获得 XML 形式的响应数据。</td>
</tr>
</tbody></table>
<h2 id="responseText-属性"><a href="#responseText-属性" class="headerlink" title="responseText 属性"></a>responseText 属性</h2><p>如果来自服务器的响应并非 XML，请使用 responseText 属性。</p>
<p>responseText 属性返回字符串形式的响应，因此您可以这样使用：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">document.getElementById(&quot;myDiv&quot;).innerHTML&#x3D;xmlhttp.responseText;</span><br></pre></td></tr></table></figure>

<h2 id="responseXML-属性"><a href="#responseXML-属性" class="headerlink" title="responseXML 属性"></a>responseXML 属性</h2><p>如果来自服务器的响应是 XML，而且需要作为 XML 对象进行解析，请使用 responseXML 属性：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">xmlDoc&#x3D;xmlhttp.responseXML;</span><br><span class="line">txt&#x3D;&quot;&quot;;</span><br><span class="line">x&#x3D;xmlDoc.getElementsByTagName(&quot;ARTIST&quot;);</span><br><span class="line">for (i&#x3D;0;i&lt;x.length;i++)</span><br><span class="line">&#123;</span><br><span class="line">    txt&#x3D;txt + x[i].childNodes[0].nodeValue + &quot;&lt;br&gt;&quot;;</span><br><span class="line">&#125;</span><br><span class="line">document.getElementById(&quot;myDiv&quot;).innerHTML&#x3D;txt;</span><br></pre></td></tr></table></figure>

<h1 id="AJAX-onreadystatechange-事件"><a href="#AJAX-onreadystatechange-事件" class="headerlink" title="AJAX - onreadystatechange 事件"></a>AJAX - onreadystatechange 事件</h1><h2 id="onreadystatechange-事件"><a href="#onreadystatechange-事件" class="headerlink" title="onreadystatechange 事件"></a>onreadystatechange 事件</h2><p>当请求被发送到服务器时，我们需要执行一些基于响应的任务。</p>
<p>每当 readyState 改变时，就会触发 onreadystatechange 事件。</p>
<p>readyState 属性存有 XMLHttpRequest 的状态信息。</p>
<p>下面是 XMLHttpRequest 对象的三个重要的属性：</p>
<table>
<thead>
<tr>
<th align="left">属性</th>
<th align="left">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="left">onreadystatechange</td>
<td align="left">存储函数（或函数名），每当 readyState 属性改变时，就会调用该函数。</td>
</tr>
<tr>
<td align="left">readyState</td>
<td align="left">存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。0: 请求未初始化1: 服务器连接已建立2: 请求已接收3: 请求处理中4: 请求已完成，且响应已就绪</td>
</tr>
<tr>
<td align="left">status</td>
<td align="left">200: “OK” 404: 未找到页面</td>
</tr>
</tbody></table>
<p>在 onreadystatechange 事件中，我们规定当服务器响应已做好被处理的准备时所执行的任务。</p>
<p>当 readyState 等于 4 且状态为 200 时，表示响应已就绪：</p>
<h2 id="实例"><a href="#实例" class="headerlink" title="实例"></a>实例</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">xmlhttp.onreadystatechange&#x3D;function()</span><br><span class="line">&#123;</span><br><span class="line">    if (xmlhttp.readyState&#x3D;&#x3D;4 &amp;&amp; xmlhttp.status&#x3D;&#x3D;200)</span><br><span class="line">    &#123;</span><br><span class="line">        document.getElementById(&quot;myDiv&quot;).innerHTML&#x3D;xmlhttp.responseText;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>注意：</strong> onreadystatechange 事件被触发 4 次（0 - 4）, 分别是： 0-1、1-2、2-3、3-4，对应着 readyState 的每个变化。</p>
<h2 id="使用回调函数"><a href="#使用回调函数" class="headerlink" title="使用回调函数"></a>使用回调函数</h2><p>回调函数是一种以参数形式传递给另一个函数的函数。</p>
<p>如果您的网站上存在多个 AJAX 任务，那么您应该为创建 XMLHttpRequest 对象编写一个<em>标准</em>的函数，并为每个 AJAX 任务调用该函数。</p>
<p>该函数调用应该包含 URL 以及发生 onreadystatechange 事件时执行的任务（每次调用可能不尽相同）：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">function myFunction()</span><br><span class="line">&#123;</span><br><span class="line">    loadXMLDoc(&quot;&#x2F;try&#x2F;ajax&#x2F;ajax_info.txt&quot;,function()</span><br><span class="line">    &#123;</span><br><span class="line">        if (xmlhttp.readyState&#x3D;&#x3D;4 &amp;&amp; xmlhttp.status&#x3D;&#x3D;200)</span><br><span class="line">        &#123;</span><br><span class="line">            document.getElementById(&quot;myDiv&quot;).innerHTML&#x3D;xmlhttp.responseText;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


    </div>

    
    
    
        <div class="reward-container">
  <div>坚持原创技术分享，您的支持将鼓励我继续分享！</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/wechatpay.png" alt="Gip886 微信支付">
        <p>微信支付</p>
      </div>

  </div>
</div>


      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/07/12/JSON%E7%AE%80%E4%BB%8B/" rel="prev" title="JSON简介">
      <i class="fa fa-chevron-left"></i> JSON简介
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/07/14/%E7%88%AC%E8%99%AB%E7%9A%84%E4%BD%BF%E7%94%A8%EF%BC%88python%EF%BC%89/" rel="next" title="爬虫的使用（python）">
      爬虫的使用（python） <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#AJAX-简介"><span class="nav-number">1.</span> <span class="nav-text">AJAX 简介</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#什么是-AJAX-？"><span class="nav-number">1.1.</span> <span class="nav-text">什么是 AJAX ？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#AJAX-工作原理"><span class="nav-number">1.2.</span> <span class="nav-text">AJAX 工作原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#AJAX是基于现有的Internet标准"><span class="nav-number">1.3.</span> <span class="nav-text">AJAX是基于现有的Internet标准</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#AJAX-创建-XMLHttpRequest-对象"><span class="nav-number">2.</span> <span class="nav-text">AJAX - 创建 XMLHttpRequest 对象</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#XMLHttpRequest-对象"><span class="nav-number">2.1.</span> <span class="nav-text">XMLHttpRequest 对象</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#创建-XMLHttpRequest-对象"><span class="nav-number">2.2.</span> <span class="nav-text">创建 XMLHttpRequest 对象</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#AJAX-向服务器发送请求请求"><span class="nav-number">3.</span> <span class="nav-text">AJAX - 向服务器发送请求请求</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#向服务器发送请求"><span class="nav-number">3.1.</span> <span class="nav-text">向服务器发送请求</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#GET-还是-POST？"><span class="nav-number">3.2.</span> <span class="nav-text">GET 还是 POST？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#GET-请求"><span class="nav-number">3.3.</span> <span class="nav-text">GET 请求</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#POST-请求"><span class="nav-number">3.4.</span> <span class="nav-text">POST 请求</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#url-服务器上的文件"><span class="nav-number">3.5.</span> <span class="nav-text">url - 服务器上的文件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#异步-True-或-False？"><span class="nav-number">3.6.</span> <span class="nav-text">异步 - True 或 False？</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#AJAX-服务器-响应"><span class="nav-number">4.</span> <span class="nav-text">AJAX - 服务器 响应</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#服务器响应"><span class="nav-number">4.1.</span> <span class="nav-text">服务器响应</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#responseText-属性"><span class="nav-number">4.2.</span> <span class="nav-text">responseText 属性</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#responseXML-属性"><span class="nav-number">4.3.</span> <span class="nav-text">responseXML 属性</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#AJAX-onreadystatechange-事件"><span class="nav-number">5.</span> <span class="nav-text">AJAX - onreadystatechange 事件</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#onreadystatechange-事件"><span class="nav-number">5.1.</span> <span class="nav-text">onreadystatechange 事件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实例"><span class="nav-number">5.2.</span> <span class="nav-text">实例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用回调函数"><span class="nav-number">5.3.</span> <span class="nav-text">使用回调函数</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Gip886"
      src="/images/%E5%A4%B4%E5%83%8F.jpg">
  <p class="site-author-name" itemprop="name">Gip886</p>
  <div class="site-description" itemprop="description">为了更美好的明天而战</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">29</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/Gip886" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;Gip886" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>



      </div>
        <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=300 height=86 src="//music.163.com/outchain/player?type=2&id=492390949&auto=1&height=66"></iframe>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Gip886</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">153k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">2:19</span>
</div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script size="300" alpha="0.6" zIndex="-1" src="/lib/canvas-ribbon/canvas-ribbon.js"></script>
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>


  <script defer src="/lib/three/three.min.js"></script>
    <script defer src="/lib/three/canvas_lines.min.js"></script>


  




  
<script src="/js/local-search.js"></script>













  

  

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","model":{"jsonPath":"/live2dw/assets/koharu.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true},"log":false,"tagMode":false});</script></body>
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/clicklove.js"></script>
</html>

